package com.ruoyi.trainingManagement.controller;

import java.util.ArrayList;
import java.util.List;


import com.ruoyi.trainingManagement.domain.Vo.CourseStudentInfoVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.trainingManagement.domain.CourseStudentInfo;
import com.ruoyi.trainingManagement.service.ICourseStudentInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 课程学生信息Controller
 * 
 * @author chenxl
 * @date 2025-06-18
 */
@RestController
@RequestMapping("/trainingManagement/CourseStudentInfo")
public class CourseStudentInfoController extends BaseController
{
    @Autowired
    private ICourseStudentInfoService courseStudentInfoService;

    /**
     * 查询课程学生信息列表
     */
    //@PreAuthorize("@ss.hasPermi('trainingManagement:CourseStudentInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(CourseStudentInfo courseStudentInfo)
    {
        startPage();
        List<CourseStudentInfo> list = courseStudentInfoService.selectCourseStudentInfoList(courseStudentInfo);
        return getDataTable(list);
    }

    /**
     * 导出课程学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseStudentInfo:export')")
    @Log(title = "课程学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CourseStudentInfo courseStudentInfo)
    {
        List<CourseStudentInfo> list = courseStudentInfoService.selectCourseStudentInfoList(courseStudentInfo);
        ExcelUtil<CourseStudentInfo> util = new ExcelUtil<CourseStudentInfo>(CourseStudentInfo.class);
        util.exportExcel(response, list, "课程学生信息数据");
    }

    /**
     * 获取课程学生信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseStudentInfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(courseStudentInfoService.selectCourseStudentInfoById(id));
    }

    /**
     * 新增课程学生信息
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseStudentInfo:add')")
    @Log(title = "课程学生信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CourseStudentInfo courseStudentInfo)
    {
        return toAjax(courseStudentInfoService.insertCourseStudentInfo(courseStudentInfo));
    }

    /**
     * 修改课程学生信息
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseStudentInfo:edit')")
    @Log(title = "课程学生信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CourseStudentInfo courseStudentInfo)
    {
        return toAjax(courseStudentInfoService.updateCourseStudentInfo(courseStudentInfo));
    }

    /**
     * 删除课程学生信息
     */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseStudentInfo:remove')")
    @Log(title = "课程学生信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(courseStudentInfoService.deleteCourseStudentInfoByIds(ids));
    }
    /*
    * 根据课程学生详情列表、课程排课详情ID更新课程学生信息
    */
    @PreAuthorize("@ss.hasPermi('trainingManagement:CourseStudentInfo:update')")
    @Log(title = "课程学生信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateCourseStudentInfoList")
    public AjaxResult updateCourseStudentInfoList(@RequestBody List<CourseStudentInfoVo> courseStudentInfoList) {
        System.out.println("接收到courseStudentInfoList参数：" + courseStudentInfoList);
        // ---------------------- 新增：参数校验（核心） ----------------------
        // 1. 校验班级列表不为空
        if (courseStudentInfoList == null || courseStudentInfoList.isEmpty()) {
            return AjaxResult.error("请传递需要更新的班级学生信息");
        }

        int totalUpdated = 0;
        for (CourseStudentInfoVo vo : courseStudentInfoList) {
            // 2. 校验单个班级的“目标班级ID”和“学生列表”不为空
            String targetId = vo.getCourseScheduleDetailsId(); // 新班级ID
            List<CourseStudentInfo> studentList = vo.getCourseStudentInfoList(); // 学生列表
            if (targetId == null || targetId.trim().isEmpty()) {
                log.warn("跳过无效班级：目标班级ID（courseScheduleDetailsId）为空");
                continue;
            }
            if (studentList == null || studentList.isEmpty()) {
                log.warn("跳过无效班级：班级[{}]的学生列表为空", targetId);
                continue;
            }

            // 3. 校验每个学生的“原始班级ID”已传递（允许为null，但需明确）
            for (CourseStudentInfo student : studentList) {
                String originalClassId = student.getCurrentCourseScheduleDetailsId();
                // 仅日志提醒，不强制拦截（因为新学生的原始班级ID就是null）
                if (originalClassId == null || originalClassId.trim().isEmpty()) {
                    log.info("学生[{}]的原始班级ID为空（可能是新学生），将匹配 course_schedule_details_id IS NULL 的记录", student.getStudentId());
                }
            }
            // -------------------------------------------------------------------

            // 执行更新（原有逻辑不变）
            int updated = courseStudentInfoService.batchUpdateCourseScheduleDetailsId(targetId, studentList);
            totalUpdated += updated;
            log.info("班级[{}]更新完成，更新行数：{}", targetId, updated);
        }

        // 返回结果（原有逻辑不变）
        return totalUpdated > 0
                ? AjaxResult.success("批量更新成功，总更新行数：" + totalUpdated)
                : AjaxResult.error("未找到可更新的学生数据（可能原始班级ID不匹配或学生不存在）");
    }
}
